//
//  VideoPlayViewController.m
//  allTest
//
//  Created by 李培根 on 2018/11/13.
//  Copyright © 2018 李培根. All rights reserved.
//

#import "VideoPlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <ShortMediaResourceLoader.h>
#import <VIResourceLoaderManager.h>
#import <KTVHTTPCache.h>

@interface VideoPlayViewController ()

@property (nonatomic, strong) UIButton * btn;

@property (nonatomic, weak) AVPlayerItem *playerItem;
@property (nonatomic, weak) AVPlayer *player;
@property (nonatomic, weak) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVURLAsset *asset;
@property (nonatomic, strong) VIResourceLoaderManager *resourceLoaderManager;
@property (nonatomic, copy) NSString *currentLink;

@end

@implementation VideoPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSString *cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *cachePath = [cachesDirectory stringByAppendingPathComponent:@"MyCache"];
    NSLog(@"cachePath:%@",cachePath);
    
    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:16384 diskCapacity:268435456 diskPath:cachePath];
    configuration.URLCache = cache;
    configuration.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
    NSURL *url = [NSURL URLWithString:@"http://httpbin.org/get"];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    NSCachedURLResponse *cachedURLResponse = [cache cachedResponseForRequest:requset];
    NSData *cacheData = cachedURLResponse.data;
    if(cacheData){//如果有缓存
        NSDictionary *dicJson=[NSJSONSerialization JSONObjectWithData:cacheData options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"local dicJson: %@",dicJson);
    } else {
        NSOperationQueue *operationQueue = [NSOperationQueue mainQueue];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:operationQueue];
        
        [[defaultSession dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSDictionary *dicJson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"remote dicJson: %@",dicJson);
        }] resume];
    }
}

- (void)ktvTest {
    NSError *error = nil;
    /*
     [KTVHTTPCache downloadSetTimeoutInterval:30];
     
     // Accept Content-Type.
     [KTVHTTPCache downloadSetAcceptContentTypes:contentTypes];
     
     // Set unsupport Content-Type filter.
     [KTVHTTPCache downloadSetUnsupportContentTypeFilter:^BOOL(NSURL * URL, NSString * contentType) {
     return NO;
     }];
     
     // Additional headers.
     [KTVHTTPCache downloadSetAdditionalHeaders:headers];
     
     // Whitelist headers.
     [KTVHTTPCache downloadSetWhitelistHeaderKeys:headers];
     */
    [KTVHTTPCache proxyStart:&error];
    if (error) {
        NSLog(@"error = %@", error);
    }
    //http://ziyan-test-img.oss-cn-beijing.aliyuncs.com/story/2018/11/06/1f5cc0fa-1bc2-42a1-8ba3-e0435e398c8e
    //http://zyvideo1.oss-cn-qingdao.aliyuncs.com/zyvd/7c/de/04ec95f4fd42d9d01f63b9683ad0
    //http://203.205.158.74/om.tc.qq.com/Aj4O61x4Cl13SR1I-XH1Hy9xqaBlJiwHJe7WdoYXLvxs/uwMRJfz-r5hgYaQXGdGnCwQsKf_dEsnq3UJztMoyPd8/o0706629f07.mp4?sdtfrom=v1010&guid=bfb41cf4010787bfcebf5ffa7df1a000&vkey=0CBC2081ECD1FD815A641D3FCB108B29BD517A1BD3FA24999D21B92E55691D23C706F676909161F4611EBCF00D90DED2D8395D19960F3736B32ADCF2AD70E1D758A03C402D78D3B6E930595ED87650D370249358E1A8E470
    //http://ziyan-test-img.oss-cn-beijing.aliyuncs.com/story/2018/11/12/621e38f1-7db8-4c25-84f7-5ab7a9ed0c13.mp4
    //https://ziyan-test-img.oss-cn-beijing.aliyuncs.com/story/2018/11/12/d6d23a0f-1709-4527-846c-ffe632c198ab.mp4
    NSString *originalLink = @"https://ziyan-img.oss-cn-qingdao.aliyuncs.com/story/2018/12/29/3805daec-43dd-4f2c-9da5-aaf8d6c15026.mp4";
    //https://ziyan-img.oss-cn-qingdao.aliyuncs.com/story/2018/12/26/b842558f-dab3-4beb-b08f-4328976ea584.mp4
    _currentLink = originalLink;
    NSString *urlLink = [KTVHTTPCache proxyURLStringWithOriginalURLString:originalLink];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:urlLink]];
    AVPlayer *play = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:play];
    layer.backgroundColor = [UIColor cyanColor].CGColor;
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    
    self.playerItem = playerItem;
    self.player = play;
    self.playerLayer = layer;
    
    
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [self.playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
    [self.playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"])
    {
        if (self.player.currentItem.status == AVPlayerItemStatusReadyToPlay)
        {
            [self.player play];
            NSString *path = [KTVHTTPCache cacheCompleteFilePathIfExistedWithURLString:_currentLink];
            NSLog(@"path = %@", path);
            NSLog(@"%@ 播放",[self class]);
        }
        else if (self.player.currentItem.status == AVPlayerItemStatusFailed)
        {
            NSLog(@"%@", self.player.currentItem.error);
            NSLog(@"播放视频失败");
        }
        else if (self.player.currentItem.status == AVPlayerItemStatusUnknown)
        {
            NSLog(@"未知状态");
        }
    }
}

- (void)playerDidFinished:(NSNotification*)noti {
    NSString *path = [KTVHTTPCache cacheCompleteFilePathIfExistedWithURLString:_currentLink];
    NSLog(@"path = %@", path);
    [self.player pause];
    [self.player seekToTime:kCMTimeZero];
    [self.player play];
    [self getVideoFile];
}

-(void)getVideoFile {
    NSString *documentDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *myPathDocument = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", @"video"]];
    NSURL *fileUrl = [NSURL fileURLWithPath:myPathDocument];
    if (_asset != nil) {
        AVMutableComposition *mixComposition = [[AVMutableComposition alloc]init];
        AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, _asset.duration) ofTrack:[[_asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0] atTime:kCMTimeZero error:nil];
        AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, _asset.duration) ofTrack:[[_asset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0] atTime:kCMTimeZero error:nil];
        AVAssetExportSession *exporter = [[AVAssetExportSession alloc]initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
        exporter.outputURL = fileUrl;
        if (exporter.supportedFileTypes) {
            exporter.outputFileType = [exporter.supportedFileTypes objectAtIndex:0] ;
            exporter.shouldOptimizeForNetworkUse = YES;
            [exporter exportAsynchronouslyWithCompletionHandler:^{
                
            }];
        }
    }
}

- (void)dealloc {
    [self.player pause];
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
    [self.playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

@end
